﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models.Database;

namespace WebAPITest.service
{

    public class UserService:IUserService
    {
        //注入数据库服务
        private readonly WebEnterpriseIIContext _db;
        public UserService (WebEnterpriseIIContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <returns></returns>
        public User GetUserByUserName(string userName)
        {
            // var user = _db.Users.FirstOrDefault(x => x.UserName == username);   
            var user = _db.Users.FirstOrDefault(x => x.UserName == userName);
            return user;
         
        }
        //服务层方法需要做的事    接口
        //1传入数据               1前端传入数据
        //2处理数据               2接口处理数据
        //3返回结果               3返回结果给前端
        /// <summary>
        /// 根据用户名判断用户是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public bool ExistUserByUserName(string userName)
        {
            return _db.Users.Any(x => x.UserName == userName);
        }
        /// <summary>
        /// 插入新用户的数据
        /// </summary>
        /// <returns></returns>
        public int AddUserByUser(string UserName, string Password, byte Salt, string Email, string NickName, byte UserLevel)
        {
            var user = new User()
            {
                UserName = UserName,
                Password = Password,
                Email = Email,
                NickName = NickName,
                UserLevel =1,
                Salt = 0,
                CreateTime=DateTime.Now
            };
            _db.Users.Add(user);
            //保存更改
            var row = _db.SaveChanges();
            return user.UserId;
        }
    }
}
